<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <template>
      <a-card class="table-page-search-wrapper">
        <titleName title="基本信息" />
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
        >
          <a-row :gutter="24">
            <a-col :md="16" :sm="16">
                    <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                        <org-tree-select v-model="form.projectId" :disabled="type === 'view'"  isAutoSelectFirst checkStrictly @select="selectOrg"></org-tree-select>
                    </a-form-model-item>
            </a-col>
            <!-- <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属分公司："
                prop="branchComId"
              >
                <SelectSubCompany
                  v-model="form.branchComId"
                  :disabled="type === 'view'"
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属项目："
                prop="projectId"
              >
                <SelectProject
                  v-model="form.projectId"
                  :disabled="type === 'view'"
                  placeholder="请选择"
                  :form="form"
                  :is-clear="id == ''"
                  key-value="branchComId"
                  @change="getOrganizePeopleList()"
                />
              </a-form-model-item>
            </a-col> -->
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="分包单位名称："
                prop="subcontractorScc"
              >
                <SelectSubcontractorCode
                  v-model="form.subcontractorScc"
                  :disabled="type === 'view'"
                  placeholder="请选择"
                  :form="form"
                  :is-clear="type == 'view'"
                  :is-edit="type != 'view'"
                  key-value="projectId"
                  @selectChange="getSubContractName"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同名称："
                prop="contractId"
              >
                <BSelect
                  v-model="form.contractId"
                  @selectChange="getSupplier"
                  :form="form"
                  :disabled="type === 'view'"
                  placeholder="从分包合同信息维护选择"
                  keyValue="subcontractorScc"
                  :init="false"
                  :request="e=>getNameList({id : form.subcontractorScc})"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同编号："
                prop="contractCode"
              >
                <BaseInput
                  v-model="form.contractCode"
                  disabled
                  placeholder="从分包合同信息维护提取"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="分包方式："
                prop="subConWay"
              >
                <BaseInput
                  v-model="form.subConWay"
                  disabled
                  placeholder="从分包合同信息维护提取"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
              v-if="exitTimeArr.length<=1"
            >
              <a-form-model-item
                label="进场时间："
                prop="inTime"
              >
                <BaseInput
                  v-model="form.inTime"
                  disabled
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
              v-if="exitTimeArr.length>1"
            >
              <a-form-model-item
                label="进场时间："
                prop="inTime"
              >
                <BSelect
                  v-model="form.inTime"
                  :disabled="type === 'view'"
                  placeholder="请选择"
                  :list="exitTimeArr"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="应完时间："
                prop="expectedTime"
              >
                <BaseInput
                  v-model="form.expectedTime"
                  disabled
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同价款(不含税)(元)："
                prop="contractFeeNoRate"
              >
                <BaseInput
                  v-model="form.contractFeeNoRate"
                  disabled
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同价款(税金)(元)："
                prop="contractRate"
              >
                <BaseInput
                  v-model="form.contractRate"
                  disabled
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同价款(含税)(元)："
                prop="contractFeeRate"
              >
                <BaseInput
                  v-model="form.contractFeeRate"
                  disabled
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="开完工日期："
                prop="confessDate"
              >
                <a-range-picker
                  v-model="form.confessDate"
                  value-format="YYYY-MM-DD"
                  :disabled="type === 'view'"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="编制完成日期："
                prop="completionDate"
              >
                <a-date-picker
                  v-model="form.completionDate"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                  disabled
                  @change="changeCompletionDate"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="编制人："
                prop="editorName"
              >
                <BaseInput
                  v-model="form.editorName"
                  disabled
                  placeholder="请选择编制人"
                />

                <!-- <SelectOrgPeople  :disabled="type === 'view'" :form="form" keyValue="projectId" init v-model="form.editorName" placeholder="请选择"> </SelectOrgPeople> -->
                <!-- <a-select :disabled="type === 'view'" placeholder="请选择" v-model="form.editorName">
                                    <a-spin v-if="fetchingOrganizePeopleList" slot="notFoundContent" size="small" />
                                    <a-select-option
                                        v-for="i in organizePeopleList"
                                        :key="i.employeeId"
                                        :value="i.employeeId"
                                        >{{ i.employeeName }}</a-select-option
                                    >
                                </a-select> -->
                <!-- <BaseInput placeholder="请输入" v-model="form.editorName"  /> -->
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="预算价款（不含税）（元）"
                prop="excludeTaxAmount"
              >
                <BaseInputNumber
                  v-model="form.excludeTaxAmount"
                  :max="99999999999999"
                  :min="0"
                  placeholder="请输入"
                  :disabled="type === 'view'"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="预算价款（增值税）（元）："
                prop="valueAddedTax"
              >
                <BaseInputNumber
                  v-model="form.valueAddedTax"
                  :max="99999999999999"
                  :min="0"
                  placeholder="请输入"
                  :disabled="type === 'view'"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item label="预算价款（含税）（元）：">
                <BaseInputNumber
                  :max="99999999999999"
                  :min="0"
                  :precision="2"
                  placeholder="请输入"
                  :value="
                                        form.valueAddedTax + form.excludeTaxAmount > 0
                                            ? form.valueAddedTax + form.excludeTaxAmount
                                            : 0
                                    "
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="24"
              :sm="8"
            >
              <a-form-model-item
                label="施工范围"
                prop="contractScope"
              >
                <BaseTextarea
                  v-model="form.contractScope"
                  placeholder="请输入"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                  :disabled="type === 'view'"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="24"
              :sm="8"
            >
              <a-form-model-item
                label="甲供材料情况："
                prop="supplyMaterials"
              >
                <BaseTextarea
                  v-model="form.supplyMaterials"
                  placeholder="请输入"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                  :disabled="type === 'view'"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="24"
              :sm="8"
            >
              <a-form-model-item
                label="编制说明："
                prop="editDesc"
              >
                <BaseTextarea
                  v-model="form.editDesc"
                  placeholder="请输入"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                  :disabled="type === 'view'"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              v-if="type === 'view'"
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="附件："
                :label-col="{ lg: { span: 3 }, sm: { span: 5 } }"
                :wrapper-col="{ lg: { span: 18 }, sm: { span: 17 } }"
              >
                <file-link :file-list="form.fileInfoVOList" />
              </a-form-model-item>
            </a-col>
            <a-col
              v-else
              :md="24"
              :sm="24"
            >
              <a-form-model-item label="附件上传">
                <l-table
                  v-if="isUpdate"
                  :upload-arrys="form.fileInfoVOList"
                  business-code="BM17"
                  @fileArrysData="fileArrysData"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <div
        v-if="type != 'view'"
        class="tool-btns page-btn-right-top"
      >
        <a-button
          v-if="form.auditStatus == 'DRAFT'"
          type="danger"
          @click="deleteDraft()"
        > 删除草稿 </a-button>
        <a-button
          v-if="form.auditStatus == 'REJECTED'"
          type="primary"
          :loading="loading.REJECTED"
          @click="submitForm('REJECTED')"
        >
          保存
        </a-button>
        <a-button
          v-else
          :loading="loading.DRAFT"
          type="primary"
          @click="submitForm('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          :loading="loading.SUBMITTED"
          type="primary"
          @click="submitForm('SUBMITTED')"
          :disabled="isAddContractName"
        > 提交 </a-button>
        <a-button
          type="primary"
          @click="closeForm()"
        > 关闭 </a-button>
      </div>
      <div
        v-else
        class="tool-btns page-btn-right-top"
      >
        <BasePrintButton
          v-if="!isAudit && form.auditStatus == 'PAST'"
          type="primary"
          :beforePrintFn="print"
        />
        <a-button
          class="ml12"
          v-if="checkVisibleInDetail"
          type="primary"
          @click="closeForm()"
        > 关闭 </a-button>
      </div>
    </template>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { addList, deteleList, findList, editList, print, addCheck } from '@/api/businessAffairs/subcontractingBudget'
import { getSccByProjectIdForAppearanceDate } from '@/api/businessAffairs/settlement'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
// import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分公司
import SelectSubcontractorCode from '@/components/Select/SelectSubcontractorCode' // 分包商
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import { isAttachment, checkVisibleInDetail } from '@/utils/util'

import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import subcontract from '@/api/legal/branchContract/subcontract'
import Vue from 'vue'
export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    SelectSubcontractorCode,
    SelectPersonByProject
  },
  data() {
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      amount: '',
      id: '',
      disabled: false,
      type: '',
      findCountQueryParam: {
        pageNo: 1,
        pageSize: 10000,
        query: {}
      },
      isUpdate: true,
      isAddContractName: false,
      rules: {
        subcontractorScc: [{ required: true, message: '请选择分包单位', trigger: 'blur' }],
        branchComId: [{ required: true, message: '请选择所属分公司 ', trigger: 'change' }],
        contractId: [{ required: true, message: '请选择合同名称', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择所属项目 ', trigger: 'change' }],
        confessDate: [{ required: true, message: ' 请选择开完工日期', trigger: 'blur' }],
        completionDate: [{ required: true, message: ' 请选择编制完成日期', trigger: 'change' }],
        editorName: [{ required: true, message: ' 请输入编制人', trigger: 'blur' }],
        excludeTaxAmount: [{ required: true, message: ' 请输入预算价款（不含税）（元）', trigger: 'blur' }],
        valueAddedTax: [{ required: true, message: '请输入预算价款（增值税）（元） ', trigger: 'blur' }],
        contractScope: [{ required: true, message: '请输入施工范围 ', trigger: 'blur' }],
        supplyMaterials: [{ required: true, message: ' 请输入甲供材料情况', trigger: 'blur' }],
        editDesc: [{ required: true, message: ' 请输入编制说明', trigger: 'blur' }]
        // inTime: [{ required: true, message: '请选择进场时间', trigger: 'blur' }],
      },
      form: { editorName: '', subcontractorScc: '' },
      token: '',
      fetchingOrganizePeopleList: false,
      organizePeopleList: [],
      init: false,
      exitTimeArr: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  async created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.id = this.$route.query.id || ''
    this.type = this.$route.query.type || 'add'
    this.$route.meta.title = this.id == '' ? '分包施工图预算新增' : '分包施工图预算编辑'
    if (this.type == 'view') {
      this.$route.meta.title = '分包施工图预算查看'
    }
    if (this.type == 'add') {
      this.form.editorName = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
      this.form.completionDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
    }
    this.findList()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_bidding_construction_plan_budget')
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.type = 'view'
          })
        }
      }
    },
    form: {
      handler(val) {
        if (val?.inTime && val?.contractFeeNoRate) {
          this.calculateTime(val.inTime, val.contractFeeNoRate)
        }
      },
      deep: true
    }
  },
  methods: {
    //选择单位
    selectOrg(val) {
        if (val && val.length) {
            this.form.branchComId = val[val.length - 2].orgId;
            this.getOrganizePeopleList()
        }
    },
    getSubContractName(e) {
      this.$set(this.form, 'subContractUnitName', e?.name)
      //  this.$set(this.form, 'inTime', e?.startDate)
      let keyArr = ['contractId', 'contractCode', 'subConWay', 'contractFeeNoRate', 'contractRate', 'contractFeeRate', 'contractName', 'expectedTime']
      keyArr.map((item) => {
        this.$set(this.form, item, null)
      })
      this.getSccByProjectIdForAppearanceDateFn(e?.name)
    },
    //获取分包退场时间
    async getSccByProjectIdForAppearanceDateFn(e) {
      if (e) {
        let req = {
          subSupplyCompany: e,
          projectId: this.form.projectId
        }
        let { data } = await getSccByProjectIdForAppearanceDate(req)
        this.exitTimeArr = []
        if (data.length > 1) {
          data.map((item) => {
            if (item.startDate) {
              this.exitTimeArr.push({
                id: item.startDate,
                name: item.startDate
              })
            }
          })
        }
        if (data.length <= 1 || this.exitTimeArr.length == 1) {
          this.$set(this.form, 'inTime', data[0]?.startDate)
        }
      }
    },
    //根据金额来计算应完时间
    calculateTime(time, sum) {
      var tian = null
      if (sum < 5000000) {
        tian = 14
      } else if (sum >= 5000000 && sum < 10000000) {
        tian = 21
      } else {
        tian = 28
      }
      let endTime = this.calculateDate(time, tian)
      this.$set(this.form, 'expectedTime', endTime)
    },
    calculateDate(date1, date2) {
      let diyDate = new Date(date1),
        date = new Date(diyDate.setDate(diyDate.getDate() + date2))
      // 拼接日期 yyyy-MM-dd 注意月份要 + 1
      date = date.getFullYear() + '-' + (date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)) + '-' + (date.getDate() > 9 ? date.getDate() : '0' + date.getDate())
      return date
    },
    //获取分包商下面的合同
    async getNameList() {
      if (this.form.projectId && this.form.subContractUnitName) {
        let req = {
          projectId: this.form.projectId,
          subSupplyCompany: this.form.subContractUnitName
        }
        // this.findCountQueryParam.query.subSupplyCompany = this.form.subcontractorName
        return subcontract
          .getSubContractByScc(req)
          .then((res) => {
            if (res.data?.length > 0) {
              res.data.map((item) => {
                item.name = item.contractName
                item.id = item.contractId
              })
            }
            return { code: 200, data: res.data }
          })
          .catch(() => {
            return { code: 200, data: [] }
          })
      }
      return { code: 200, data: [] }
    },
    getSupplier(e) {
      this.$set(this.form, 'contractCode', e?.contractCode)
      this.$set(this.form, 'subConWay', e?.contractTypeStr)
      this.$set(this.form, 'contractFeeNoRate', e?.contractExTaxAmount)
      this.$set(this.form, 'contractRate', e?.contractRate)
      this.$set(this.form, 'contractFeeRate', e?.contractInTaxAmount)
      this.$set(this.form, 'contractName', e?.contractName)
      this.addCheckContractName(this.form.contractId)
    },
    async addCheckContractName(id) {
      let data = await addCheck(id)
      if (data.code == 200) {
        if (!data.data.result) {
          this.$message.warning('该合同已新增,不能重复新增')
        }
        this.isAddContractName = !data.data.result
      }
    },
    print() {
      return print({ id: this.id }).then((res) => {
        console.log(res)
        return res.data.content
      })
    },
    getTime(date, dateString, type, name) {
      this[type][name] = dateString
      console.log(this[type][name])
    },
    clearData() {
      if (this.isInit) {
      }
      this.isInit = true
    },
    //获取项目下的人员列表
    getOrganizePeopleList() {
      if (!this.form.projectId) return
      let params = {
        id: this.form.projectId
      }
      this.clearData()
      this.fetchingOrganizePeopleList = true
      getOrganizePeopleList(params).then((res) => {
        this.fetchingOrganizePeopleList = false
        let obj = {}
        res.data = res.data.reduce((cur, next) => {
          obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
          return cur
        }, []) //设置cur默认类型为数组，并且初始值为空的数组

        this.organizePeopleList = res.data
      })

      console.log(this.organizePeopleList)
    },
    // 查询详情
    findList() {
      if (this.id) {
        this.isUpdate = false
        findList({ id: this.id }).then((res) => {
          this.isUpdate = true
          res.data.confessDate = [res.data.workStartDate, res.data.workEndDate]
          this.form = { ...res.data }
          this.$nextTick(() => {
            this.form.subcontractorScc = res.data?.subcontractorScc
          })

          // this.getOrganizePeopleList()
        })
      }
    },
    fileArrysData(val) {
      this.form.fileInfoVOList = val
    },

    changeCompletionDate(value, dateString) {
      this.form.completionDate = dateString
      console.log(dateString)
    },
    changeConfessDate(value, dateString) {
      console.log(this.form.confessDate)
      this.form.confessDate = dateString
      this.$set(this.form, 'confessDate', dateString)
      console.log(this.form.confessDate)
    },
    // 删除草稿
    deleteDraft() {
      let that = this
      console.log(this.form)
      this.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return deteleList({ id: that.id })
            .then((res) => {
              that.$message.success('删除成功！')
              that.closeForm()
            })
            .catch((res) => {
              that.$message.warning('删除失败！')
            })
        },
        onCancel() {
          // console.log('Cancel')
        }
      })
    },

    // 提交表单
    submitForm(auditStatus) {
      this.setProcessConfig = null;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (isAttachment(this, auditStatus, this.form.fileInfoVOList)) return
          this.loading[auditStatus] = true
          this.form.auditStatus = auditStatus
          this.form.workStartDate = this.form.confessDate[0]
          this.form.workEndDate = this.form.confessDate[1]
          this.submitApprovalConfirm(auditStatus =='SUBMITTED'?this.processConfig:6, (flag)=>{
            if(!flag) {
              this.loading[auditStatus] = false
              return
            }
          if (this.id != '') {
            console.log(this.form)
            editList(this.form).then((res) => {
              this.loading[auditStatus] = false
              if (res.code == '200') {
                this.$message.success('修改成功')
                 if(auditStatus =='SUBMITTED') {
                  //提交时，返回id
                      this.businessId = res.data.id || this.id;
                      this.setProcessConfig = this.processConfig;
                      return
                  }else{
                    this.closeForm()
                 }
              }
            })
          } else {
            addList(this.form).then((res) => {
              this.loading[auditStatus] = false
              if (res.code == '200') {
                this.$message.success('新增成功')
                if (auditStatus =='SUBMITTED') {
                  //提交时，返回id
                    this.businessId = res.data.id;
                    this.setProcessConfig = this.processConfig;
                    return
                  }else{
                    this.closeForm()
                 }
              }
            })
          }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    // 关闭表单
    closeForm() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
.foot-btn {
  display: flex;
  justify-content: space-between;
}
.ant-calendar-picker {
  width: 100%;
}
</style>
